//
// Copyright (c) Microsoft Corporation.  All rights reserved.
//
//
// Use of this sample source code is subject to the terms of the Microsoft
// license agreement under which you licensed this sample source code. If
// you did not accept the terms of the license agreement, you are not
// authorized to use this sample source code. For the terms of the license,
// please see the license agreement between you and Microsoft or, if applicable,
// see the LICENSE.RTF on your install media or the root of your tools installation.
// THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES.
//
#include <windows.h>
#include <pehdr.h>
#include <romLdr.h>
#include <oal.h>
#include <bootStore.h>
#include <bootStoreUtils.h>

//------------------------------------------------------------------------------

UINT32
BootStoreReadFromImageLib(
    HANDLE hStore,
    UINT32 index,
    RECT* pRect,
    VOID* pBuffer,
    UINT32 bufferSize
    )
{
    UINT32 rc = -1;
    UINT64 startPos, pos;
    UINT32 size;
  
    // Store original position
    if (!BootStoreGetPos(hStore, &startPos)) goto cleanUp;
    pos = startPos;

    // Seek to record beginning
    while (index-- > 0)
        {
        // Read record size
        if (BootStoreRead(hStore, &size, sizeof(size)) != sizeof(size))
            goto cleanUp;
        // Get next record position
        pos += size + sizeof(size);
        // Skip it
        if (!BootStoreSeek(hStore, pos)) goto cleanUp;
        }

    // Read record size
    if (BootStoreRead(hStore, &size, sizeof(size)) != sizeof(size))
        goto cleanUp;

    // Now read image position
    if (BootStoreRead(hStore, pRect, sizeof(*pRect)) != sizeof(*pRect))
        goto cleanUp;

    // Read binary image
    rc = BootStoreReadBinCompressed(hStore, pBuffer, bufferSize);
    
cleanUp:
    // Move back to original position
    BootStoreSeek(hStore, startPos);
    return rc;
}

//------------------------------------------------------------------------------

